const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    saveBtn: false,
    isWritePhoto: true, //写入照片的功能是否开启
    reloadBtn: false
  },

  imageLoad() {
    wx.getSetting({
      success: setting => {
        console.log();
        if (setting.authSetting["scope.writePhotosAlbum"] === false) {
          this.setData({
            isWritePhoto: false
          })
        } else {
          this.setData({
            isWritePhoto: true
          })
        }
      },
      fail: e => {
        app.showToast("获取配置失败");
      }
    })
    this.setData({
      saveBtn: true,
      reloadBtn: false
    })
  },

  imageError(e) {
    this.setData({
      saveBtn: false,
      reloadBtn: true
    })
  },


  //保存二维码
  saveQrcode() {
    if (!this.data.isWritePhoto) {
      wx.openSetting({
        success: setting => {
          if (setting.authSetting["scope.writePhotosAlbum"]) {
            this.setData({
              isWritePhoto: true
            })
            this.saveQrcodeToPhoto();
          } else {
            this.setData({
              isWritePhoto: false
            })
          }
        },
        fail: e => {
          app.showToast("打开设置失败");
        }
      })
    } else {
      this.saveQrcodeToPhoto();
    }
  },

  saveQrcodeToPhoto() {
    wx.showLoading({
      mask: true,
    })
    wx.downloadFile({
      url: this.data.data.qrcode,
      success: res => {
        if (res.statusCode === 200) {
          const {
            tempFilePath
          } = res;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: results => {
              console.log(results)
              app.showToast("打水码已保存", "success")
            },
            fail: e => {
              wx.hideLoading()
              if (e.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
                this.setData({
                  isWritePhoto: false
                })
              }
              app.showToast("保存文件失败")
            }
          })
        }
      },
      fail: e => {
        wx.hideLoading()
        app.showToast("下载文件失败")
      }
    })
  },


  reloadQrcode() {
    this.getQrcodeInfo();
  },

  getQrcodeInfo() {
    app.ajax({
      url: "Common/Equipment/getQrcode",
      data: {
        equipment_sn: this.eq_sn
      },
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            data: res.data.data
          });
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误,请稍后重试")
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.eq_sn = options.eq_sn;
    this.getQrcodeInfo();
  },
})